<template>
  <div>
    <DockerTitle titleText="开设处方"></DockerTitle>
    <el-divider />
    <el-table ref="wytable" :data="tableData">
      <el-table-column type="selection" width="55" />
      <el-table-column label="药品名称" prop="drugName"></el-table-column>
      <el-table-column label="药品规格" prop="drugFormat"></el-table-column>
      <el-table-column label="单价" prop="drugPrice"></el-table-column>
      <el-table-column label="用法用量">
        <template #default="scope">
          <el-input v-model="scope.row.drugUsage"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="数量">
        <template #default="scope">
          <el-input-number v-model="scope.row.drugNumber" :min="1" :max="20" />
        </template>
      </el-table-column>
      <el-table-column>
        <template #header>
          <el-button size="small" type="primary" @click="dialog.show = true">添加</el-button>
          <el-button size="small" type="danger" @click="delRow">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-button style="margin-top: 20px" type="primary" @click="save">保存</el-button>
    <el-dialog
        v-model="dialog.show"
        title="添加药品"
        width="800px"
        :close-on-click-modal="false">
      <DrugList @addRow="addRow" v-if="dialog.show"
                v-model:show="dialog.show"
      ></DrugList>
    </el-dialog>
  </div>
</template>

<script setup>
import DockerTitle from '@/components/doctor/title'
import { ref, reactive } from 'vue'
import DrugList from './druglist'
import { post } from '@/util/axios'
import { RegisterStore } from '@/stores/counter'
import dayjs from 'dayjs'
const useRegisterStore = RegisterStore()
const register = useRegisterStore.get()
const wytable = ref()
const tableData = ref([])
const dialog = reactive({
  show: false
})
function addRow (row) {
  for (const i in tableData.value) {
    if (row.id === tableData.value[i].id) {
      tableData.value[i].drugNumber++
      return
    }
  }
  tableData.value.push(row)
}
function delRow () {
  const rows = wytable.value.getSelectionRows()
  if (rows.length) {
    for (const i in rows) {
      const id = rows[i].id
      for (const j in tableData.value) {
        if (id === tableData.value[j].id) {
          tableData.value.splice(j, 1)
          break
        }
      }
    }
  } else {
    ElMessage.error('未选中任何疾病项目')
  }
}

function save () {
  const wyform = []
  for (const i in tableData.value) {
    wyform.push({
      registerId: register.value.id,
      drugId: tableData.value[i].id,
      drugUsage: tableData.value[i].drugUsage,
      drugNumber: tableData.value[i].drugNumber,
      creationTime: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
      drugState: '已开立'
    })
  }
  console.dir(wyform)
  post('/prescription/add', { content: JSON.stringify(wyform) }, content => {
    console.dir(content)
  })
}
</script>

<style scoped lang="scss">
</style>
